package service

import (
	"context"
	"os"
	"os/signal"
	"sync"
	"syscall"
)

type Server struct {
	ctx  context.Context
	stop context.CancelFunc
	wg   sync.WaitGroup
}

func NewServer() *Server {
	ctx, stop := context.WithCancel(context.Background())
	return &Server{ctx: ctx, stop: stop}
}

func (s *Server) Server(function func()) {
	s.wg.Add(1)
	go func() {
		defer s.wg.Done()
		s.server_contain(function)
	}()
}

func (s *Server) server_contain(function func()) {
	for {
		select {
		case <-s.ctx.Done():
			return
		default:
			// func
			function()
		}
	}
}

func (s *Server) Wait() {
	// 监听系统信号
	sigChan := make(chan os.Signal, 1)
	signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)
	<-sigChan // 等待一个信号
	s.stop()  // 触发取消

	// 等待所有goroutine完成
	s.wg.Wait()
}
